package fragmentson;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import activity.SonActivity;
import bean.MessageForSimple;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import util.cache.ImageLoader;
import util.dialog.DialogForPhoto;
import util.myview.CircleImageView;

/**
 * 用户信息
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class UserInfo extends BackHandledFragment {

	private View rootView;
	private int SYS_INTENT_REQUEST = 0XFF01,CAMERA_INTENT_REQUEST = 0XFF02,IMAGE_CUT = 1;
	public String photoPath,filename="";
	private Uri photoUri,imageUri;
	private CircleImageView iv_circleview;
	private Bitmap bmp;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_userinfo, null);
		initView();
		initData();
		return rootView;
	}

	private void initData(){
		ApiUtil.getApiService().getUserinfo(DemoApplication.getToken()).enqueue(new Callback<MessageForSimple>() {
			@Override
			public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
				try {
					MessageForSimple entity = response.body();
					if(entity.getCode().equals("10008")){
						((TextView) rootView.findViewById(R.id.tv_nice)).setText(entity.getData().getUsername());
						((TextView) rootView.findViewById(R.id.tv_phone)).setText(entity.getData().getTelephone());
						new ImageLoader(getActivity()).DisplayImage(entity.getData().getHeadimg(), ((CircleImageView) rootView.findViewById(R.id.iv_photo)));
					}else{
						Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Call<MessageForSimple> call, Throwable t) {
				Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
			}
		});
	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) rootView.findViewById(R.id.tv_title)).setText(R.string.main_title_userinfo);
		rootView.findViewById(R.id.ll_head).setOnClickListener(listener);
		rootView.findViewById(R.id.ll_nice).setOnClickListener(listener);
		rootView.findViewById(R.id.tv_exit).setOnClickListener(listener);
	}

	public static UserInfo newInstance() {
		UserInfo fragment = new UserInfo();
		Bundle bundle = new Bundle();
		fragment.setArguments(bundle);
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				case R.id.ll_head:
					DialogForPhoto dialog = new DialogForPhoto(getActivity());
					dialog.setSureListener(new DialogForPhoto.Sure() {
						@Override
						public void onSure(int item) {
							switch (item){
								case 1:
									cameraPhoto();
									break;
								case 2:
									systemPhoto();
									break;
								default:
									break;
							}
						}
					});
					dialog.show();
					break;
				case R.id.ll_nice:
					((SonActivity) getActivity()).addFragment(EditInfo.newInstance(((TextView) rootView.findViewById(R.id.tv_nice)).getText().toString()));
					break;
				case R.id.tv_exit:
					DemoApplication.exit2Login(getActivity());
					break;
				default:
					break;
			}
		}
	};

	/**
	 * 打开系统相册
	 */
	private void systemPhoto() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, SYS_INTENT_REQUEST);
	}

	/**
	 * 调用相机拍照
	 */
	private void cameraPhoto() {
		String sdStatus = Environment.getExternalStorageState();
		/* 检测sd是否可用 */
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			Toast.makeText(getActivity(),"SD卡不可用",Toast.LENGTH_LONG).show();
			return;
		}
		//图片名称 时间命名
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date(System.currentTimeMillis());
		filename = format.format(date);
		//创建File对象用于存储拍照的图片 SD卡根目录
		//File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);
		//存储至DCIM文件夹
		File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		File outputImage = new File(path,filename+".jpg");
		try {
			if(outputImage.exists()) {
				outputImage.delete();
			}
			outputImage.createNewFile();
		} catch(IOException e) {
			e.printStackTrace();
		}
		//将File对象转换为Uri并启动照相程序
		imageUri = Uri.fromFile(outputImage);
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); //照相
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //指定图片输出地址
		//拍完照startActivityForResult() 结果返回onActivityResult()函数
		startActivityForResult(intent, CAMERA_INTENT_REQUEST);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == SYS_INTENT_REQUEST
				&& resultCode == getActivity().RESULT_OK&&data !=null) {
			cameraCamera(data);
		} else if (requestCode == CAMERA_INTENT_REQUEST
				&& resultCode == getActivity().RESULT_OK) {
			cameraCamera();
		} else if (requestCode == IMAGE_CUT
				&& resultCode == getActivity().RESULT_OK) {
			 bmp = data.getParcelableExtra("data");
			if(bmp==null){
				if(photoUri!=null){
					try {
						bmp = BitmapFactory.decodeStream(
								getActivity().getContentResolver().openInputStream(photoUri));
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			photoPath = photoUri.getEncodedPath();
			ApiUtil.getApiService().saveHeadImg(DemoApplication.getToken(), ApiUtil.upload(photoPath)).enqueue(new Callback<MessageForSimple>() {
				@Override
				public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
					try {
						MessageForSimple entity = response.body();
						if(entity.getCode().equals("10008")){
							((CircleImageView) rootView.findViewById(R.id.iv_photo)).setImageBitmap(bmp);
						}else{
							Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				@Override
				public void onFailure(Call<MessageForSimple> call, Throwable t) {
					Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
				}
			});

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 拍照后获取照片
	 */
	private void cameraCamera() {
		Uri uri = null;
		if(imageUri!=null){
			uri = imageUri;
		}
		Intent intent = getImageClipIntent(uri);
		//广播刷新相册
		Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		intentBc.setData(imageUri);
		getActivity().sendBroadcast(intentBc);
		startActivityForResult(intent, IMAGE_CUT);
	}

	/**
	 * @param data
	 * 相册选择后后获取照片
	 */
	private void cameraCamera(Intent data) {
		Uri uri = data.getData();
		// 相册中文件绝对路径
		Intent intent = getImageClipIntent(uri);
		startActivityForResult(intent, IMAGE_CUT);
	}

	/**
	 * 获取剪切后的图片
	 */
	public Intent getImageClipIntent(Uri uri) {
		//图片名称 时间命名
		File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
		File outputImage = new File(path,"1.jpg");
		try {
			if(outputImage.exists()) {
				outputImage.delete();
			}
			outputImage.createNewFile();
		} catch(IOException e) {
			e.printStackTrace();
		}
		//将File对象转换为Uri并启动照相程序
		photoUri = Uri.fromFile(outputImage);

		Intent intent = new Intent("com.android.camera.action.CROP", null);
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("scale", true);
		intent.putExtra("crop", true);
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);// 输出图片大小
		intent.putExtra("outputY", 200);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("return-data", false);
		return intent;
	}


	@Override
	public boolean onBackPressed() {
		return false;
	}
	
}
